import * as http from "http";
import * as url from "url";
import type BetterExportPdfPlugin from "./main";
import * as fs from "fs/promises";
import * as path from "path";
import { renderMarkdown } from "./render";
import { createWebview } from "./render";
import { exportToPDF } from "./pdf";
import type { TConfig } from "./modal";

export class HttpServer {
  private server: http.Server | null = null;
  private plugin: BetterExportPdfPlugin;
  private port: number;

  constructor(plugin: BetterExportPdfPlugin, port: number = 3000) {
    this.plugin = plugin;
    this.port = port;
  }

  public start() {
    if (this.server) {
      console.log("Server already running");
      return;
    }

    this.server = http.createServer((req, res) => {
      this.handleRequest(req, res);
    });

    this.server.listen(this.port, () => {
      console.log(`Better Export PDF HTTP server started on port ${this.port}`);
    });

    this.server.on("error", (err) => {
      console.error("HTTP Server error:", err);
    });
  }

  public stop() {
    if (this.server) {
      this.server.close(() => {
        console.log("Better Export PDF HTTP server stopped");
      });
      this.server = null;
    }
  }

  private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse) {
    try {
      const parsedUrl = url.parse(req.url || "", true);
      const pathname = parsedUrl.pathname || "";
      
      // 启用CORS
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
      res.setHeader("Access-Control-Allow-Headers", "Content-Type");
      
      // 处理预检请求
      if (req.method === "OPTIONS") {
        res.writeHead(200);
        res.end();
        return;
      }

      // 健康检查端点
      if (req.method === "GET" && pathname === "/health") {
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ 
          status: "OK", 
          version: this.plugin.manifest.version,
          timestamp: new Date().toISOString()
        }));
        return;
      }

      // 通过POST请求生成PDF
      if (req.method === "POST" && pathname === "/convert") {
        let body = "";
        req.on("data", chunk => {
          body += chunk.toString();
        });

        req.on("end", async () => {
          try {
            let requestData;
            const contentType = req.headers["content-type"];
            
            if (contentType && contentType.includes("application/json")) {
              requestData = JSON.parse(body);
            } else if (contentType && contentType.includes("application/x-www-form-urlencoded")) {
              const params = new URLSearchParams(body);
              requestData = {
                content: params.get("content"),
                filename: params.get("filename") || "document"
              };
            } else {
              requestData = { content: body, filename: "document" };
            }
            
            const { content, filename } = requestData;
            
            if (!content) {
              res.writeHead(400, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: "Content is required" }));
              return;
            }

            // @ts-ignore
            const basePath = this.plugin.app.vault.adapter.basePath;
            // 修复路径拼接问题，使用正确的相对路径
            const tempDir = path.join(".obsidian", "plugins", "better-export-pdf", "temp");
            
            // 确保临时目录存在
            try {
              await fs.access(tempDir);
            } catch {
              await fs.mkdir(tempDir, { recursive: true });
            }

            // 使用path.basename确保不会引入完整路径，并清理非法字符
            const baseFilename = path.basename(filename || 'temp-document', path.extname(filename || 'temp-document'));
            const safeFilename = baseFilename.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5\-]/g, '_');
            const tempFilePath = path.join(tempDir, `${safeFilename}.md`);
            const outputFilePath = path.join(tempDir, `${safeFilename}.pdf`);

            // 写入临时Markdown文件
            await fs.writeFile(tempFilePath, content, 'utf-8');
						console.log("新起点====")
            // 创建完全兼容的虚拟文件对象
            const virtualFile = {
              path: tempFilePath,
              name: path.basename(tempFilePath),
              basename: path.basename(tempFilePath, '.md'),
              extension: 'md',
              stat: {
                ctime: Date.now(),
                mtime: Date.now(),
                size: content.length
              },
              getFullPath() {
                return this.path;
              },
              vault: this.plugin.app.vault
            };
						console.log("结束点====")
            // 渲染Markdown
            const rendered = await renderMarkdown({
              app: this.plugin.app,
              file: virtualFile as any,
              config: {
                pageSize: "A4",
                marginType: "1",
                showTitle: true,
                open: false,
                scale: 100,
                landscape: false,
                displayHeader: true,
                displayFooter: true,
              }
            });
						console.log("结束点2====")

            // 创建webview并生成PDF
            const webview = createWebview(1.0);
            
            // 等待webview加载完成
            await new Promise<void>((resolve) => {
              const loadHandler = () => {
                webview.removeEventListener('dom-ready', loadHandler);
                resolve();
              };
              webview.addEventListener('dom-ready', loadHandler);
              // 先添加事件监听器，再设置src
              // @ts-ignore
              webview.src = 'about:blank';
            });
						console.log("结束点3====")
            // 导出PDF
            await exportToPDF(
              outputFilePath,
              { ...this.plugin.settings } as TConfig & BetterExportPdfPlugin["settings"],
              webview,
              {
                doc: rendered.doc,
                frontMatter: rendered.frontMatter,
                file: virtualFile
              }
            );

            // 读取生成的PDF文件
            const pdfBuffer = await fs.readFile(outputFilePath);

            // 清理临时文件
            await fs.unlink(tempFilePath);
            await fs.unlink(outputFilePath);

            // 返回PDF文件
            const encodedFilename = encodeURIComponent(`${safeFilename}.pdf`);
            res.writeHead(200, {
              "Content-Type": "application/pdf",
              "Content-Disposition": `attachment; filename*=UTF-8''${encodedFilename}`,
            });
            res.end(pdfBuffer);
          } catch (error) {
            console.error("Error generating PDF:", error);
            res.writeHead(500, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "Failed to generate PDF", details: (error as Error).message }));
          }
        });
        return;
      }

      // 读取本地文件并生成PDF
      if (req.method === "GET" && pathname.startsWith("/convert/local/")) {
        try {
          const filename = decodeURIComponent(pathname.substring("/convert/local/".length));
          
          // @ts-ignore
          const basePath = this.plugin.app.vault.adapter.basePath;
          // 修复路径问题，确保正确处理文件路径
          let filePath: string;
          // 检查是否为绝对路径
          if (path.isAbsolute(filename)) {
            filePath = filename;
          } else {
            // 检查是否已经包含basePath前缀
            if (filename.startsWith(basePath)) {
              filePath = filename;
            } else {
              filePath = path.join(basePath, filename);
            }
          }
          
          // 检查文件是否存在
          try {
            await fs.access(filePath);
          } catch {
            res.writeHead(404, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "File not found" }));
            return;
          }

          // 创建完全兼容的虚拟文件对象
          const fileStat = await fs.stat(filePath);
          const virtualFile = {
            path: filePath,
            name: path.basename(filePath),
            basename: path.basename(filePath, '.md'),
            extension: 'md',
            stat: {
              ctime: fileStat.ctime.getTime(),
              mtime: fileStat.mtime.getTime(),
              size: fileStat.size
            },
            getFullPath() {
              return this.path;
            },
            vault: this.plugin.app.vault
          };

          // 渲染Markdown
          const rendered = await renderMarkdown({
            app: this.plugin.app,
            file: virtualFile as any,
            config: {
              pageSize: "A4",
              marginType: "1",
              showTitle: true,
              open: false,
              scale: 100,
              landscape: false,
              displayHeader: true,
              displayFooter: true,
            }
          });

          // 创建webview并生成PDF
          const webview = createWebview();
          
          // 等待webview加载完成
          await new Promise<void>((resolve) => {
            const loadHandler = () => {
              webview.removeEventListener('dom-ready', loadHandler);
              resolve();
            };
            webview.addEventListener('dom-ready', loadHandler);
            // @ts-ignore
            webview.src = 'data:text/html,<html></html>';
          });

          // 输出文件路径
          const outputFilePath = filePath.replace(/\.md$/, '.pdf');

          // 导出PDF
          await exportToPDF(
            outputFilePath,
            { ...this.plugin.settings } as TConfig & BetterExportPdfPlugin["settings"],
            webview,
            rendered
          );

          // 读取生成的PDF文件
          const pdfBuffer = await fs.readFile(outputFilePath);

          // 设置响应头，返回PDF文件
          res.setHeader('Content-Type', 'application/pdf');
          res.setHeader('Content-Disposition', `inline; filename*=UTF-8''${encodeURIComponent(virtualFile.basename)}.pdf`);
          res.writeHead(200);
          res.end(pdfBuffer);
        } catch (error) {
          console.error("Error generating PDF:", error);
          res.writeHead(500, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "Failed to generate PDF", details: (error as Error).message }));
        }
        return;
      }

      // 404 处理
      res.writeHead(404, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "Endpoint not found" }));
    } catch (error) {
      console.error("Error handling request:", error);
      res.writeHead(500, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "Internal server error", details: (error as Error).message }));
    }
  }
}
